
<html>
   <head>
   <link type="text/css" rel="stylesheet" href="/game.css">
   </head>
   <body>
   		<g:if test="${bs==null}">
   			No board session found!
   		</g:if>
   		<g:else>
   			<h2><div id="gameType">Game - ---</div></h2>
   				<table>
   				<tr>
   					<td>
   						Players
   					</td>
   					<td>
   						<font class="score">&nbsp;&nbsp;&nbsp;Score</font>
   					</td>
   					<td>
   						<div id="result">&nbsp;</div>
   					</td>
   				</tr>
   				<tr>
   					<td>
   						<div id="player1">Player 1 : ${bs.player1.name}</div>
   					</td>
   					<td>
   						<font class="score">&nbsp;&nbsp;&nbsp;${score1}</font>
   					</td>
   					<td>
   						<div id="resultPlayer1">&nbsp;</div>
   					</td>
   				</tr>
   				<tr>
   					<td>
		   				<div id="player2">Player 2 : ${bs.player2.name}</div>
   					</td>
   					<td>
   						<font class="score">&nbsp;&nbsp;&nbsp;${score1}</font>
   					</td>
   					<td>
   						<div id="resultPlayer2">&nbsp;</div>
   					</td>
   				</tr>
   				</table>
   				<div id="nextActor">Expected to act : ---</div>
   			<hr>
   			<table>
   			<tr>
   			<td>&nbsp;</td>
   			<td><div id="pos1">.</div></td>
   			<td><div id="pos2">.</div></td>
   			<td><div id="pos3">.</div></td>
   			<td><div id="pos4">.</div></td>
   			<td><div id="pos5">.</div></td>
   			<td><div id="pos6">.</div></td>
   			<td>&nbsp;</td>
   			</tr>
   			<tr>
   			<td><div id="pos0">.</div></td>
   			<td colspan="6">&nbsp;</td>
   			<td><div id="pos7">.</div></td>
   			</tr>
   			<tr>
   			<td>&nbsp;</td>
   			<td><div id="pos13">.</div></td>
   			<td><div id="pos12">.</div></td>
   			<td><div id="pos11">.</div></td>
   			<td><div id="pos10">.</div></td>
   			<td><div id="pos9">.</div></td>
   			<td><div id="pos8">.</div></td>
   			<td>&nbsp;</td>
   			</tr>
   			</table>
   			<div id="points"></div>
   			<br><br><br>
   			<a href="select" onclick="return toggleDebug();"><div id="debugButton">Show debug</div></a>
   			<div id="debugEnableAutoClient"></div>
   			<font class="debug"><div id="gameIdDiv"></div></font>
   			<font class="debug"><div id="discrepanciesDiv"></div></font>
   			<font class="debug"><div id="debugOutputDiv"></div></font>
   <script type="text/javascript" src="/_ah/channel/jsapi"></script>
   <g:javascript>
     
     	var showDebug = false;
	var debugInfo = "";
	var gameId = "<hr>Game id : ${bs.sessionId}";
	var enableAutoClient = "<hr><a href='select' onclick='return toggleAutoPlay();'>Enable auto client</a>";
	function toggleDebug() {
		if (showDebug==true) {
			document.getElementById("debugButton").innerHTML="Show debug";
			document.getElementById("gameIdDiv").innerHTML="";
			document.getElementById("debugEnableAutoClient").innerHTML="";
		} else {
			document.getElementById("debugButton").innerHTML="Hide debug";
			document.getElementById("gameIdDiv").innerHTML=gameId;
			document.getElementById("debugEnableAutoClient").innerHTML=enableAutoClient;
		}
		showDebug = !showDebug;
		displayDebugInfo(null);
		return false;
	}
	
	function displayDebugInfo(info) {
		if (info!=null) {
			debugInfo = "<hr>" + info +  debugInfo;
		}
		if (showDebug==true) {
			document.getElementById("debugOutputDiv").innerHTML=debugInfo;
		} else {
			document.getElementById("debugOutputDiv").innerHTML="";
		}
	}
     	
     openChannel = function() {
<g:if test="${bs.player1.sessionId==clientSessionId}">
        var token = '${bs.player1.channelToken}';
        var message = 'player1';
</g:if>
<g:if test="${bs.player2.sessionId==clientSessionId}">
        var token = '${bs.player2.channelToken}';
        var message = 'player2';
</g:if>

        var channel = new goog.appengine.Channel(token);
        
        var handler = {
          'onopen': function() {},
          'onmessage': function(m) { var state = eval("("+m.data+")");
          	deltaDiscrepancy = getTimeDiscrepancy(state["timestamp"]);
          	displayDebugInfo("Channel " + deltaDiscrepancy +"<br>"+ m.data);
          	updateState(state);
          },
          'onerror': function() {},
          'onclose': function() {}
        };
        var socket = channel.open(handler);

      }
      
    
     initialize = function() {
        openChannel();
      }
      //alert("2");
      
	  
	  updateScore = function(state, model) {
	  	if (state != null) {
	  	  document.getElementById("points").innerHTML="<b>Game over</b> Player 1=<b>"+model[7]+"</b>&nbsp;&nbsp;&nbsp;Player 2=<b>"+model[0]+"</b>";
	  	} else {
		  document.getElementById("points").innerHTML="Player 1=<b>"+model[7]+"</b>&nbsp;&nbsp;&nbsp;Player 2=<b>"+model[0]+"</b>";
		}
 	  }
 	  
 	  var myActor = "UNDEFINED"
 	  var myName = "UNDEFINED"
 	  var player1Name = "UNDEFINED"
 	  var player2Name = "UNDEFINED"
 	  
 	  updateNextActor = function(nextActor, player1, player2, roundDuration) {
 	    if (nextActor=="NONE" || nextActor=="ENGINE") {
 	    	document.getElementById("nextActor").innerHTML="&nbsp;";
 	    	stopTimer();
 	    	return;
 	    }
 	    
 	    var name = player1["name"]
 	    if (nextActor=="PLAYER_2") {
 	    	name = player2["name"]
 	    }
 	    var message = "Expected to act : <b>" + name + "</b>";
 	    if (nextActor == myActor) {
 	    	if (nextActor=="PLAYER_2" || nextActor=="PLAYER_1") 
 	    	{ 
 	    		startActingRoundTimer(roundDuration,true); 
 	    	}
 	    } else {
	 		startActingRoundTimer(roundDuration,false);
	 	}
 	  }
 	  
 	      
     selectBucket = function(index) {
        var xmlhttp;
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
  		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			displayDebugInfo("HTTP:" + xmlhttp.status +" "+ xmlhttp.responseText);
    			//do nothing
    		} 
    		else if (xmlhttp.readyState==4 && xmlhttp.status!=0)
    		{
    			displayDebugInfo("HTTP " + xmlhttp.status +"<br>"+ xmlhttp.responseText);
    		}
  		}
  		displayDebugInfo("Select bucket " + index);
  		xmlhttp.open("POST","/games/${bsId}/?clientSessionId=${clientSessionId}&arg="+index+"&discrepancy="+deltaDiscrepancy,true);
		xmlhttp.send();
		return false;
      }
      
    calculateTime = function(lastUpdated,roundDuration) {
    	var now = new Date().getTime() - deltaDiscrepancy;
    	var result = roundDuration-Math.round((now-lastUpdated)/1000);
    	displayDebugInfo("date="+new Date()+" now=" + now + " lastUpdated=" + lastUpdated + " roundDuration="+roundDuration+" deltaDiscrepancy= " + deltaDiscrepancy+" result="+result); 
    	return result;
    }

    getTimeDiscrepancy = function(timestamp) {
    	var now = new Date().getTime();
		var delta = now - timestamp
    	return delta;
    }
    
	updateState = function(state) {		
	  	var myTurn = 0;
    	var playerNumber = 0;
    	var playerId = "${playerId}";
    	
    	if (playerId != "") {
    		if (playerId==state["player1"]["userId"]) {
    			myActor = "PLAYER_1"
    			myName = state["player1"]["name"]
    			playerNumber = 1;
    			
    		} else if (playerId==state["player2"]["userId"]) {
    			myActor = "PLAYER_2"
    			myName = state["player2"]["name"]
    			playerNumber = 2
    		}
    	}
    	
    	updateScore(state["state"], state["model"]);
		updateNextActor(state["nextActor"],state["player1"],state["player2"],calculateTime(state["lastUpdated"], state["roundDuration"]));
		updateGameState(state["state"], state["winner"],state["player1score"],state["player2score"]);
    	
    	if ((playerNumber==1 && state["nextActor"]=="PLAYER_1")) {
    			myTurn = 1;
    	} else if (playerNumber==2 && state["nextActor"]=="PLAYER_2") {
    			myTurn = 1;
    	}    			
	    
	  	document.getElementById("pos0").innerHTML=state["model"][0];
	  	document.getElementById("pos7").innerHTML=state["model"][7];
	  	firstIndexThisRound=-1;
	 	for (var i=1, len=7; i<len; ++i ){
  			if (myTurn==1 && playerNumber==1 && state["model"][i]>0) { // add links
  				firstIndexThisRound = i;
  				document.getElementById("pos"+i).innerHTML="<a ID='mylink"+i+"' href='select' onclick=\"return selectBucket('"+i+"');\">"+state["model"][i]+"</a>";
  			} else {
  				document.getElementById("pos"+i).innerHTML=state["model"][i];
  			}
		}
		
		for (var i=8, len=state["model"].length; i<len; ++i ){ // add links
  			if (myTurn==1 && playerNumber==2 && state["model"][i]>0) {
  				firstIndexThisRound = i;
  				document.getElementById("pos"+i).innerHTML="<a ID='mylink"+i+"' href='select' onclick=\"return selectBucket('"+i+"');\">"+state["model"][i]+"</a>";
  			} else {
  				document.getElementById("pos"+i).innerHTML=state["model"][i];
  			}
		}
		
			if (autoPlayEnabled==true && myTurn==1) {
				selectBucket(firstIndexThisRound);
			} 
 	  }
 	  	  
	  updateGameState = function(state,winner,player1Score,player2Score) {
	  	 if (state!=null) { // game finished
	  	 	if (winner=="PLAYER_1") {
	  	 		document.getElementById("player1").innerHTML = "Player 1 : <b>" + player1Name +" won</b>"
	  	 	} 
	  	 	else if (winner=="PLAYER_2") {
	  	 		document.getElementById("player2").innerHTML = "Player 2 : <b>" + player2Name +" won</b>"
	  	 	}
	  	 	if (state=="TIMED_OUT") { document.getElementById("nextActor").innerHTML="<b>Game timed out and was canceled</b>" }
	  	 	document.getElementById("result").innerHTML = "&nbsp;&nbsp;&nbsp;Result";
	  	 	var p1Score = player1Score;
	  	 	if (player1Score>0) { p1Score = "+" + p1Score; }
	  	 	var p2Score = player2Score;
	  	 	if (player2Score>0) { p2Score = "+" + p2Score; }
	  	 	document.getElementById("resultPlayer1").innerHTML = "&nbsp;&nbsp;&nbsp;"+p1Score;
	  	 	document.getElementById("resultPlayer2").innerHTML = "&nbsp;&nbsp;&nbsp;"+p2Score;
	  	 }
	  }
	  
	  var deltaDiscrepancy = 0
	  
	  loadState = function() {
	  	var xmlhttp;
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
  		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			//alert(xmlhttp.getAllResponseHeaders());
    			var state = eval("("+xmlhttp.responseText+")");
    			deltaDiscrepancy = getTimeDiscrepancy(state["timestamp"]);
    			displayDebugInfo("HTTP:" + xmlhttp.status +" " + deltaDiscrepancy + " " + xmlhttp.responseText);
    			player1Name = state["player1"]["name"]
    			player2Name = state["player2"]["name"]
   				updateState(state);
   				
   				document.getElementById("gameType").innerHTML="Game - " + state.gameType;
    		} 
    		else if (xmlhttp.readyState==4 && xmlhttp.status==301)
    		{
    			alert("Redirected to " + xmlhttp.location);
    		}
    		else if (xmlhttp.readyState==4 && xmlhttp.status!=0)
    		{
    			displayDebugInfo("HTTP:" + xmlhttp.status +" "+ xmlhttp.responseText);
    		}
  		}
  		displayDebugInfo("Fetching initial state");
  		xmlhttp.open("GET","/games/${bsId}/?clientSessionId=${clientSessionId}",true);
		xmlhttp.send();
	  }
	  
	  sendTimeout = function() {
	  	var xmlhttp;
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
  		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			displayDebugInfo("HTTP:" + xmlhttp.status +" "+ xmlhttp.responseText);
    		}
    		else if (xmlhttp.readyState==4 && xmlhttp.status==402)
    		{
    			displayDebugInfo("HTTP:" + xmlhttp.status +" "+ xmlhttp.responseText);
    		} 
    		else if (xmlhttp.readyState==4 && xmlhttp.status!=0)
    		{
    			displayDebugInfo("r" + xmlhttp.status +" "+ xmlhttp.responseText);
    		}
  		}
  		//alert("Timeout");
  		displayDebugInfo("Timing out");
  		xmlhttp.open("POST","/games/${bsId}/?clientSessionId=${clientSessionId}&arg=timeout",true);
		xmlhttp.send();
	  }
	  
	  var roundDurationSecs
	  var timerID = null
	  var timerRunning = false
	  var delay1second = 1000
	  var roundMessage
	  var cancelGameOnTimeOut

	  function startActingRoundTimer(roundDuration,thisClientIsActing)
{
	stopTimer()
    // Set the length of the timer, in seconds
    roundDurationSecs = roundDuration
    cancelGameOnTimeOut = thisClientIsActing
    startTimer()
}

function stopTimer()
{
    if(timerRunning)
        clearTimeout(timerID)
    timerRunning = false
}

function startTimer()
{	
    if (roundDurationSecs<=0)
    {
    	document.getElementById("nextActor").innerHTML="";
        stopTimer()
        sendTimeout();
    }
    else
    {
    	if (cancelGameOnTimeOut) {
	    	document.getElementById("nextActor").innerHTML= "Expected to act : <b>You --- " + roundDurationSecs + "</b> seconds left";
        } else {
        	document.getElementById("nextActor").innerHTML= "Expected to act : <b>Opponent --- " + roundDurationSecs + "</b> seconds left";
        }
        self.status = roundDurationSecs
        roundDurationSecs = roundDurationSecs - 1
        timerRunning = true
        timerID = self.setTimeout("startTimer()", delay1second)
    }
}

var firstIndexThisRound=-1;
var autoPlayEnabled=false;
toggleAutoPlay = function () {
	if (autoPlayEnabled==true) {
		enableAutoClient = "<hr><a href='select' onclick='return toggleAutoPlay();'>Enable auto client</a>";
		autoPlayEnabled = false;
	} else {
		autoPlayEnabled = true;
		enableAutoClient = "<hr><a href='select' onclick='return toggleAutoPlay();'>Disable auto client</a>";
		if (firstIndexThisRound!=-1){
			selectBucket(firstIndexThisRound);
		}
	}
	document.getElementById("debugEnableAutoClient").innerHTML=enableAutoClient
	return false;
}

	 setTimeout(loadState, 100);
	 
     setTimeout(initialize, 200);
     
     
</g:javascript>
   		
   		</g:else>
   		
   	</body>
</html>